package com.ayoldi.podcastusbsync.downloader;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.ayoldi.podcastusbsync.configurator.ConfigurationManager;

public class FeedsDownloaderManager {

	static Logger LOG = Logger.getLogger(FeedsDownloaderManager.class);
	private static final long DEFAULT_FEED_MONITOR_PERIOD=120000;
	
	ConfigurationManager configManager;
	
	List<FeedsDownloaderThread> feedsDownloader;
	long feedMonitorPeriod;
	
	
	
	public FeedsDownloaderManager(ConfigurationManager configManager){
		this.configManager=configManager;
		try{
			feedMonitorPeriod=Long.parseLong(configManager.getGlobalOptions().getFeedMonitorPeriod())*1000;

		}
		catch (Exception e){
			LOG.warn("Could not parse feed monitor period: "+ configManager.getGlobalOptions().getFeedMonitorPeriod()+". Using default "+DEFAULT_FEED_MONITOR_PERIOD);
		}
	}
	
	public void startFeedsDownloader(){
		feedsDownloader=new ArrayList<FeedsDownloaderThread>();
		
		FeedsDownloaderThread feedsDownloaderThread=new FeedsDownloaderThread(configManager,feedMonitorPeriod);
		feedsDownloaderThread.start();
		this.feedsDownloader.add(feedsDownloaderThread);
				
	}

	public void stop() {
		for (FeedsDownloaderThread thread : feedsDownloader){
			thread.setStopped(true);
		}
		boolean allThreadsStopped=false;
		while (!allThreadsStopped){
			allThreadsStopped=true;
			for (FeedsDownloaderThread thread : feedsDownloader){
				if (!thread.isStopped()){
					allThreadsStopped=false;
				}
			}
			if (!allThreadsStopped){
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

}
